package top.shiyiri.web;

import top.shiyiri.pojo.Cart;
import top.shiyiri.pojo.User;
import top.shiyiri.service.OrderService;
import top.shiyiri.service.impl.OrderServiceImpl;
import top.shiyiri.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/2/10 12:12
 */
public class OrderServlet extends BaseServlet {

    private OrderService orderService = new OrderServiceImpl();
    /**
     * 生成订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //获取userId
        User user = (User) req.getSession().getAttribute("user");
        //如果没有登录则跳转到登录页面
        if (user == null) {
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            return;//不再执行后续的代码
        }
        System.out.println("OrderServlet 程序在【"+Thread.currentThread().getName()+"】中");
        Integer id = user.getId();
        //调用 orderService.createOrder(Cart,userId)
        String order = orderService.createOrder(cart, id);//返回订单号
//        try {
//            order = orderService.createOrder(cart, id);
//            JDBCUtils.commitAndClose();//提交事务
//        } catch (Exception e) {
//            JDBCUtils.rollbackAndClose();//回滚事务
//            e.printStackTrace();
//        }
        //重定向不能获取request域中数据
//        req.setAttribute("orderId", order);
        req.getSession().setAttribute("orderId", order);
        System.out.println("订单号：" + order);
        //重定向 /pages/cart/checkout.jsp
        resp.sendRedirect("pages/cart/checkout.jsp");
    }
}
